package com.tongcheng.service.impl;

import com.tongcheng.mapper.GoodsMapper;
import com.tongcheng.pojo.Goods;
import com.tongcheng.service.GoodsService;
import com.tongcheng.utils.ConversionDateUtils;
import com.tongcheng.utils.UploadFile;
import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ClassName: GoodsServiceImpl
 * Description: TODO
 * Author: lcl
 * Date: 2020/11/26 14:27
 * Version: 1.0
 */
@Service
public class GoodsServiceImpl implements GoodsService{
    @Autowired(required = false)
    private GoodsMapper goodsMapper;
    /**
     * 根据商家id或商品id或商品名称或商品状态查询对应的商品信息
     * @param merchant_id
     * @return
     */
    @Override
    public List<Map> queryGoods(Integer merchant_id,Integer goods_id,String goods_name,Integer goods_shelves_id) {

        List<Map> mapList = goodsMapper.queryGoods(merchant_id,goods_id,goods_name,goods_shelves_id);
        //时间转换
        for (Map map:mapList) {
            String merchant_join_date = ConversionDateUtils.conversionDateStringUtils(map.get("merchant_join_date"));
            String goods_create_time = ConversionDateUtils.conversionDateStringUtils(map.get("goods_create_time"));
            map.put("merchant_join_date",merchant_join_date);
            map.put("goods_create_time",goods_create_time);
        }
        //查询出商品性
        return mapList;
    }

    /**
     * 商品状态信息查询
     * @return
     */
    @Override
    public List<Map> queryGoodsShelves() {
        List<Map> mapList = goodsMapper.queryGoodsShelves();
        return mapList;
    }

    /**
     * 商品列表查询
     * @param goods_id
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public List<Map> queryGoodById(Integer goods_id) {
        /**
         * 查询商品基本信息：
         * 商品名称，goods_name
         * 商品描述，goods_describe
         * 商品状态，goods_shelves_id
         * 商品状态名称，goods_shelves_name
         * 商品首页大图地址，goods_home_img_url
         * 商品创建时间，goods_create_time
         */
        Map map1 = goodsMapper.queryGoodById(goods_id);
        //时间转换
        String goods_create_time = ConversionDateUtils.conversionDateStringUtils(map1.get("goods_create_time"));
        map1.put("goods_create_time",goods_create_time);
        /**
         * 商品所属商家信息
         * 商家di，merchant_id
         * 商家名称，merchanr_name
         * 商家姓名：user_name
         * 商家联系方式：user_iphone
         * 商家地址，merchant_site
         * 商家状态id merchant_status_id
         * 商家状态名称 merchant_status_name
         * 商家注册成功时间 merchant_join_date
         * 商家注册状态信息 register_state
         */

        Map map2 = goodsMapper.queryGoodMerchant(goods_id);
        //时间转换
        String merchant_join_date = ConversionDateUtils.conversionDateStringUtils(map2.get("merchant_join_date"));
        map2.put("merchant_join_date",merchant_join_date);
        /**
         * 商品详情页图片地址查询
         * goods_img_id
         * goods_img_url
         */
        List<Map> mapList1 = goodsMapper.queryGoodImgUrl(goods_id);
        Map map3 = new HashMap();
        //将图片地址保存为数组形式
        Object[] imgArrays = new String[mapList1.size()];
        for (int i = 0;i < imgArrays.length;i++){
            imgArrays[i] = mapList1.get(i).get("goods_img_url");
        }
        map3.put("imgArrays",imgArrays);

        /**
         * 商品规格
         * 商品规格id：goods_specifications_id
         * 商品原价：goods_original_price
         * 商品促销价：goods_promotion
         * 商品成本价：goods_cost_price
         * 商品购买限制：goods_buy_restrictions
         * 商品库存：goods_inventory
         */
        Map map4 = goodsMapper.queryGoodSpec(goods_id);
        /**
         * 商品浏览信息
         * 商品浏览信息id：goods_browse_id
         * 最近浏览时间：goods_browse_time
         * 商品访问量：goods_view
         * 今日访问量：goods_today_view
         * 本周访问量：goods_week_view
         * 本月访问量：goods_month_view
         * 商城排名：goods_ranking
         */
        Map map5 = goodsMapper.queryBrowse(goods_id);
        //时间转换
        String goods_browse_time = ConversionDateUtils.conversionDateStringUtils(map5.get("goods_browse_time"));
        map5.put("goods_browse_time",goods_browse_time);
        //获得指定商品浏览量的商城排名
        Map map = goodsMapper.queryGoodRank(goods_id);
        System.out.println(map.get("rank"));
        map5.put("goods_ranking",map.get("rank"));
        /**
         * 商品销售总量:goods_sell_sum
         * 今日销售量:goods_sell_today_sum
         * 本周销售量:goods_sell_week_sum
         * 本月销售量:goods_sell_month_sum
         * 商品销量排行:goods_sell_ranking
         * 商品退货数量:goods_return
         */
        //根据商品id获取当前商品的销售总量
        Map map6 = new HashMap();
        Integer goods_sell_sum = goodsMapper.queryGoodOrder(goods_id);
        if (goods_sell_sum == null){
            goods_sell_sum = 0;
        }
        map6.put("goods_sell_sum",goods_sell_sum);
        //根据商品id查询当前商品的日销售量
        Integer goods_sell_today_sum = goodsMapper.queryTodaySum(goods_id);
        if (goods_sell_today_sum == null){
            goods_sell_today_sum = 0;
        }
        map6.put("goods_sell_today_sum",goods_sell_today_sum);
        //根据商品id查询当前商品的周销量
        Integer goods_sell_week_sum = goodsMapper.queryWeekSum(goods_id);
        if (goods_sell_week_sum == null){
            goods_sell_week_sum = 0;
        }
        map6.put("goods_sell_week_sum",goods_sell_week_sum);
        //根据商品id查询当前商品的月销量
        Integer goods_sell_month_sum = goodsMapper.queryMonthSum(goods_id);
        if (goods_sell_month_sum == null){
            goods_sell_month_sum = 0;
        }
        map6.put("goods_sell_month_sum",goods_sell_month_sum);
//        查询商品的销量排行
        Integer rank = goodsMapper.querySellRank(goods_id);
        map6.put("goods_sell_ranking",rank);
        //查询商品的退货数量
        Integer goods_return = goodsMapper.queryReturn(goods_id);
        if (goods_return == null){
            goods_return = 0;
        }
        map6.put("goods_return",goods_return);
        /**
         * 商品流水信息
         * 流水id：goods_water_id
         * 销售总流水：goods_water_total
         * 今日流水：goods_water_today
         * 本周流水：goods_water_week
         * 本月流水：goods_water_month
         * 流水排行：goods_water_ranking
         * 退款总计：goods_refund_sum
         */
        Map map7 = new HashMap();
        //根据商品id获得该商品的总流水
        BigDecimal goods_water_total = goodsMapper.queryWaterTotal(goods_id);
        if (goods_water_total == null){
            goods_water_total = new BigDecimal(0);
        }
        map7.put("goods_water_total",goods_water_total);
        //根据商品id获得该商品的今日流水
        BigDecimal goods_water_today = goodsMapper.queryWaterToday(goods_id);
        if (goods_water_today == null){
            goods_water_today = new BigDecimal(0);
        }
        map7.put("goods_water_today",goods_water_today);

        //根据商品id获得该商品的本周流水
        BigDecimal goods_water_week = goodsMapper.queryWaterWeek(goods_id);
        if (goods_water_week == null){
            goods_water_week = new BigDecimal(0);
        }
        map7.put("goods_water_week",goods_water_week);

        //根据商品id获得该商品的本月流水
        BigDecimal goods_water_month = goodsMapper.queryWaterMonth(goods_id);
        if (goods_water_month == null){
            goods_water_month = new BigDecimal(0);
        }
        map7.put("goods_water_month",goods_water_month);

        //根据商品id获得该商品流水排行
        Integer goods_water_ranking = goodsMapper.queryWaterRank(goods_id);
        map7.put("goods_water_ranking",goods_water_ranking);

        List<Map> mapList = new ArrayList<>();
        mapList.add(map1);
        mapList.add(map2);
        mapList.add(map3);
        mapList.add(map4);
        mapList.add(map5);
        mapList.add(map6);
        mapList.add(map7);
        return mapList;
    }

    /**
     * 商品图片类型查询
     * @return
     */
    @Override
    public List<Map> queryGoodImgType() {
        List<Map> mapList = goodsMapper.queryGoodImgType();
        return mapList;
    }
    /**
     * 商品添加
     * @param map
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public int addGoods(Map map) {
        //获取商品创建时间
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(date);
        Date goods_create_time = ConversionDateUtils.conversionDateUtils(time);
        map.put("goods_create_time",goods_create_time);

        //添加商品信息
        int result = goodsMapper.addGoods(map);
        //添加成功后。返回商品id
        Integer goods_id = (Integer) map.get("goods_id");
        System.out.println("打印得到的商品id" +goods_id);
        //维护商品与商家的中间表
        int re = goodsMapper.addGoodMerchant(map);
        //得到商品详情图片地址
        String[] goodsDetailImgList = (String[]) map.get("goodsDetailImgList");
        int res = 0;
        //添加商品详情图片地址
        for (int i = 0; i < goodsDetailImgList.length;i++){
            res = goodsMapper.addImgUrl(goods_id,goodsDetailImgList[i]);
        }
        //为新增商品建立浏览信息表，方便之后维护商品的浏览信息
        int resl = goodsMapper.addGoodsBrowse(goods_id);
        //添加商品规格信息
        int res2 = goodsMapper.addGoodSpec(map);
        return res2;
    }
    /**
     * 根据商品id编辑对应的商品信息
     * @param map
     * @return
     */
    @Override
    public int editGoods(Map map) {
//        int result = goodsMapper.editGoods(goods_id);
        return 1;
    }
    /**
     * 商品首页图片文件地址解析返回
     * @param goods
     * @return
     */
    @Override
    public Map uploadGoodsHomeImg(Goods goods,HttpServletRequest request) throws IOException, FileUploadException {
        System.out.println("====serviceGoods====" + goods.getFile());
        MultipartFile[] file = new MultipartFile[1];
        file[0] = goods.getFile();
        String[] imgPath = UploadFile.uploadFile(request,file);
        Map map = new HashMap();
        map.put("goods_home_img_url",imgPath[0]);
        System.out.println(imgPath[0]);
        return map;
    }
    /**
     * 商品详情页上传(商品详情页图片文件集合)
     * @param fileArrays
     * @param request
     * @return
     */
    @Override
    public String[] uploadGoodsImgUrl(MultipartFile[] fileArrays, HttpServletRequest request) throws IOException, FileUploadException {
        String[] imgPath = UploadFile.uploadFile(request,fileArrays);
        return imgPath;
    }
    /**
     * 查询热销商品
     * @return
     */
    @Override
    public List<Map> querySellLikeGoods() {
        List<Map> mapList = goodsMapper.querySellLikeGoods();
        return mapList;
    }
    /**
     * 查询所有参加团购商品
     * @return
     */
    @Override
    public List<Map> queryGroupBookGoods(String merchanr_goods_name) {
        List<Map> mapList = goodsMapper.queryGroupBookGoods(merchanr_goods_name);
        return mapList;
    }
    /**
     * 查询所有商品列表接口(可根据商品名称或店铺名称实现模糊查询)
     * @param merchanr_goods_name
     * @return
     */
    @Override
    public List<Map> queryGoodsApp(String merchanr_goods_name) {
        List<Map> mapList = goodsMapper.queryGoodsApp(merchanr_goods_name);
        return mapList;
    }
    /**
     * 根据商品id查询对应的商品详细信息(app端)
     * @param goods_id
     * @return
     */
    @Override
    public List<Map> queryGoodByIdApp(Integer goods_id) {
        List<Map> mapList = new ArrayList<>();
        //根据商品id查询出该商品下的所有销售量
        Integer goods_sell_sum = goodsMapper.queryInById(goods_id);
        if (goods_sell_sum == null){
            goods_sell_sum = 0;
        }
        //查询出商品的信息
        Map map1 = goodsMapper.queryGoodByIdApp(goods_id,goods_sell_sum);
        /**
         * 时间转换
         */
        String merchant_join_date = ConversionDateUtils.conversionDateStringUtils(map1.get("merchant_join_date"));
        map1.put("merchant_join_date",merchant_join_date);
        String goods_create_time = ConversionDateUtils.conversionDateStringUtils(map1.get("goods_create_time"));
        map1.put("goods_create_time",goods_create_time);
        mapList.add(map1);
        //根据商品id查询到商品的详情页图片
        List<Map> mapList1 = goodsMapper.queryGoodImgUrl(goods_id);
        Object[] imgArrays = new String[mapList1.size()];
        for (int i = 0;i < imgArrays.length;i++){
            imgArrays[i] = mapList1.get(i).get("goods_img_url");
        }
        Map map = new HashMap();
        map.put("imgArrays",imgArrays);
        mapList.add(map);

        /**
         * 商品浏览量操作（当用户访问此接口时，浏览量增加）
         */
        //根据商品id查询出商品的浏览信息
        Map<String,Object> map2 = goodsMapper.queryGoodBrowse(goods_id);
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(date);
        Date goods_browse_time = ConversionDateUtils.conversionDateUtils(time);
        map2.put("goods_browse_time",goods_browse_time);

        Integer goods_view = (Integer) map2.get("goods_view");
        map2.put("goods_view", goods_view + 1);

        Integer goods_today_view = (Integer) map2.get("goods_today_view");
        map2.put("goods_today_view", goods_today_view + 1);

        Integer goods_week_view = (Integer) map2.get("goods_week_view");
        map2.put("goods_week_view", goods_week_view + 1);

        Integer goods_month_view = (Integer) map2.get("goods_month_view");
        map2.put("goods_month_view", goods_month_view + 1);
        //更新浏览量
        int result = goodsMapper.updateGoodBrowse(map2);
        return mapList;
    }
    /**
     * 根据商品id查询该商品的规格信息（app返回参数）
     * @param goods_id
     * @return
     */
    @Override
    public List<Map> queryGoodSpecById(Integer goods_id) {
        List<Map> mapList = goodsMapper.queryGoodSpecById(goods_id);
        return mapList;
    }

    /**
     * 根据商品id下架对应的商品（可多个商品操作）
     * @param goodsList
     * @return
     */
    @Override
    public int deleGoods(Integer[] goodsList) {
        int res = 0;
        for (int i = 0; i < goodsList.length;i++){
            res = goodsMapper.deleGoods(goodsList[i]);
        }
        return res;
    }
}
